package com.canbot.u05.versionupdate

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_update.*

/**
 * 版本更新-信息展示
 * Created by xh on 2017/11/24.
 */

class UpdateActivity : Activity() {

    // 自身是否更新中
    private var mSelfIsUpdating = false

    // 是否等待安装自身
    private var mSelfIsWaiting = false

    /**
     * 更新胸口版本更新信息
     */
    private val mHandler = Handler(Handler.Callback { message ->
        when (message.what) {
            // 胸口更新失败
            UPDATE_VERSION_FAILURE -> {
                //MsgSendUtils.sendStringMsg(MsgType.CANCEL_UPDATE_VERSION, "cancel update version")
                showToast("版本更新失败, 请稍后尝试")
                finishDelay()
                Log.e(TAG, "胸口版本更新失败")
            }
            // 更新自身更新进度信息
            UPDATE_VERSION_SHOW_INFO -> {
                mSelfIsUpdating = true
                if (update_info_layout.visibility != View.VISIBLE) {
                    update_info_layout.visibility = View.VISIBLE
                }
                update_info_tv.text = message.obj as String
            }
            // 胸口无新版本
            NOT_NEW_VERSION -> {
                mSelfIsUpdating = false
                Log.e(TAG, "胸口版本无需更新")
            }
            // 胸口版本准备完毕，可以安装了
            VERSION_READY -> {
                mSelfIsUpdating = true
                mSelfIsWaiting = false
                VersionUpdateUtils.getInstance(this@UpdateActivity).startInstallSelf()
            }
            // 胸口版本更新完毕
            VERSION_UPDATE_FINISHED -> {
                mSelfIsUpdating = false
                finishDelay()
                Log.e("VersionUpdateUtils", "胸口版本更新完毕")
            }
        }
        false
    })

    private fun showToast(string: String) {
        this.runOnUiThread {
            val toast = Toast.makeText(this, string, Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.BOTTOM, 0, 0)
            toast.show()
        }
    }

    private fun finishDelay() {
        mHandler.postDelayed({
            finish()
        }, 2000)
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    private fun hideBottomUIMenu() {
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        window.decorView.setOnSystemUiVisibilityChangeListener {
            var uiOptions = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_FULLSCREEN //全屏
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION //隐藏导航栏
                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
            uiOptions = uiOptions or 0x00001000
            window.decorView.systemUiVisibility = uiOptions
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

        setContentView(R.layout.activity_update)

        initView(intent)
    }

    override fun onResume() {
        super.onResume()
        hideBottomUIMenu()
    }

    private fun initView(intent: Intent) {
        val selfUpdateStatus = intent.getIntExtra(CHECK_SELF_UPDATE_STATUS, 0)
        if (selfUpdateStatus >= 0) {
            VersionUpdateUtils.getInstance(this).startUpdateVersion(mHandler)
            if (selfUpdateStatus == 1) {
                mSelfIsUpdating = true
                update_info_layout.visibility = View.VISIBLE
                update_info_tv.text = "开始获取下载链接"
                Log.e(TAG, "胸口 开始版本更新")
            }
        }
    }

    override fun onBackPressed() {}

    override fun onDestroy() {
        super.onDestroy()
        VersionUpdateUtils.getInstance(this).cancelUpdate()
        //MsgSendUtils.sendStringMsg(MsgType.CANCEL_UPDATE_VERSION, "cancel version update")
    }

    companion object {
        private val TAG = UpdateActivity::class.java.simpleName

        /**
         * 胸口版本更新检测状态
         * 1：有新版本，0：检查更新失败，-1：没有新版本
         */
        const val CHECK_SELF_UPDATE_STATUS = "checkSelfUpdateStatus"

        /**
         * 自身版本更新失败
         */
        const val UPDATE_VERSION_FAILURE = 10001

        /**
         * 更新胸口版本更新信息展示
         */
        const val UPDATE_VERSION_SHOW_INFO = 10002

        /**
         * 胸口无新版本
         */
        const val NOT_NEW_VERSION = 1003

        /**
         * 胸口版本准备完毕
         */
        const val VERSION_READY = 1004

        /**
         * 胸口版本更新完毕
         */
        const val VERSION_UPDATE_FINISHED = 1005
    }
}
